//
//  SchoolAddHornViewController.swift
//  HoneyBee
//
//  Created by point on 2018/1/30.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit

import SwiftyJSON
private let kCellID = "kCellID"


class SchoolAddHornViewController: BaseViewController {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var topHeight: NSLayoutConstraint!
    fileprivate var videoArr:[String] =  [String]()
    var schoolID:Int = 0
    fileprivate var rightBtn: UIButton!
    var currentModel:[InstitutionResourceModel] =  [InstitutionResourceModel]()
    
    @IBOutlet weak var doneBtn: UIButton!
    @IBOutlet weak var clickBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "校园角"
        topHeight.constant = LayoutCommon.navHeight
        collectionView.backgroundColor = UIColor.init(hex: "f4f6f8")
        setupUI()
        doneBtn.fastCornerRadius(value: 15)
        view.backgroundColor = UIColor.init(hex: "f4f6f8")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    @IBAction func clickDone(_ sender: UIButton) {
        if currentModel.count < 2 {
            self.hudLoadMessage("为了更好展现, 不测少于2张图片或者视频")
            return
        }
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    @IBAction func clickNextBtn(_ sender: UIButton) {
        guard let  index = navigationController?.viewControllers.index(of: self) else {
            return
        }
        
        if let aIndex = (navigationController?.viewControllers[index - 4]) {
            navigationController?.popToViewController(aIndex, animated: true)
        }
        
    }
    
    @objc func click(btn:UIButton) {
        let vc = SchoolAddUploadHornViewController()
        let uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertController.Style.actionSheet)
        
        let takePhoto = UIAlertAction(title:"上传视频", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            vc.type = 1
            self.navigationController?.pushViewController(vc, animated: true)
            
        }
        let photoLib = UIAlertAction(title:"上传图片", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            vc.type = 0
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        let cancel = UIAlertAction(title:"取消", style:UIAlertAction.Style.cancel) { (action:UIAlertAction)in
        }
        
        uploadAlertController.addAction(takePhoto)
        uploadAlertController.addAction(photoLib)
        uploadAlertController.addAction(cancel)
        present(uploadAlertController, animated: true, completion: nil)
    }
}
extension SchoolAddHornViewController: HornCollectionViewCellDelegate {
    
    func clickHornCollectionViewCellDel(index: Int) {
        self.hudLoad("正在删除")
        let id = self.currentModel[index].id
        let url = kHost + kdeleteInstitutionResource + "".apiF(time: "1", sign: "") + "&id=" + String(id)
        TempNetTool.post(url, parameters: nil, progress: nil, success: { [weak self](result) in
            self?.currentModel.remove(at: index)
            self?.hudHide()
            self?.hudLoadMessage("删除成功")
            self?.collectionView.reloadData()
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudError()
        }
        
    }
    
    func clickHornCollectionViewCellPlay(index: Int) {
        let videoPath:String = self.currentModel[index].path
        guard let playerURL = URL(string: videoPath) else { return }
        guard let vc = SHBAVController(url: playerURL) else {return }
        self.present(vc, animated: true, completion: nil)
    }
    
    
}

extension SchoolAddHornViewController {
    func loadData() {
        let dict = ["id":schoolID,
                    "pageNo":"1",
                    "pageSize":"1000",
                    "timestamp":"1",
                    "sign":"1"
            ] as [String : Any]
        
        let str = kHost + kqueryInstitutionResource + dict.formatApi()
        
        TempNetTool.post(str, parameters: dict, progress: nil
            , success: { [unowned self](result) in
                let json = JSON(result as Any)
                self.currentModel = InstitutionResourceModel.format(fromJson: json)
                self.collectionView.reloadData()
        }) { (error) in
            
        }
    }
}


extension SchoolAddHornViewController: UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.currentModel.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellID, for: indexPath) as! HornCollectionViewCell
        cell.configModel(model: self.currentModel, index: indexPath)
        cell.delegate = self
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
}

extension SchoolAddHornViewController {
    fileprivate func setupUI(){
        let btn = UIButton(type: .custom)
        rightBtn = btn
        btn.addTarget(self, action: #selector(click(btn:)), for: .touchUpInside)
        btn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        btn.setImage(UIImage(named: "VideoUpload"), for: .normal)
        self.navItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        self.title = "校园角"
        self.collectionView.register(UINib(nibName: "HornCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kCellID)
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        let sizeW:CGFloat = CGFloat(Int((kScreenW - 30) / 2))
        layout.itemSize = CGSize(width: sizeW, height: sizeW + 50)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
}

